﻿var utils = {
    TabAdd: function (tabContainerId, title, content, url) {
        //if ($('#' + tabContainerId).tabs('exists', title)) {
        //    $('#' + tabContainerId).tabs('select', title);
        //} else {
        //    if (content == "") {
        //        content = '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>';
        //    }
        //    $('#' + tabContainerId).tabs('add', {
        //        title: title,
        //        content: content,
        //        closable: true
        //    });
        //}
        if ($('#' + tabContainerId).tabs('exists', title)) {
            //关闭tab
            $('#' + tabContainerId).tabs('close', title);
        }
        content = '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>';
        $('#' + tabContainerId).tabs('add', {
            title: title,
            content: content,
            closable: true
        });
    },
    // Add by xingzheng.song 160307
    TabAddIntoParent: function (tabContainerId, title, content, url, isCanClose) {
        var closable = isCanClose == undefined ? true : isCanClose;
        
        var jq = top.jQuery;
        var $container = jq('#' + tabContainerId);
        if ($container.tabs('exists', title)) {
            $container.tabs('select', title);

            // 更新当前tab  
            $container.tabs('update', {
                tab: $container.tabs('getSelected'),
                options: {
                    content: '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>'
                    //href: url
                }
            });
        } else {
            if (content == "") {
                content = '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>';
            }
            $container.tabs('add', {
                title: title,
                content: content,
                closable: closable
            });
        }
    },
    GetSelectedTab: function () {
        return top.jQuery('#tabContainer').tabs('getSelected');
    },
    // Add by xingzheng.song 160330
    UpdateSelectedTab: function (url) {
        // 更新选中tab  
        var jq = top.jQuery;
        var $container = jq('#tabContainer');
        $container.tabs('update', {
            tab: $container.tabs('getSelected'),
            options: {
                content: '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>',
                //或者 href : '';  
            }
        });
    },
    //add by zhiping.li 160316
    ColseCurrentTab: function (tabContainerId) {
        var jq = top.jQuery;
        var $container = jq('#' + tabContainerId);
        // 更新当前tab 
        var current_tab = $container.tabs('getSelected');
        var current_index = $container.tabs('getTabIndex', current_tab);
        $container.tabs("close", current_index);
    },
    Loading: function () {
        $("<div class=\"datagrid-mask\"></div>").css({ display: "block", width: "100%", height: $(window).height() }).appendTo("body");
        $("<div class=\"datagrid-mask-msg\"></div>").html("正在运行，请稍候。。。").appendTo("body").css({ display: "block", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 });
    },
    LoadingHidden: function () {
        $(".datagrid-mask").remove();
        $(".datagrid-mask-msg").remove();
    },
    Confirm: function (msg) {
        $.messager.confirm('确认', msg, function (r) {
            return r;
        });
    },
    MsgShow: function (title, msg, isAlert) {  //弹出提醒框alert 
        if (title == "") title = "消息提示";
        if (isAlert !== undefined && isAlert) {
            $.messager.alert(title, msg);
        } else {
            $.messager.show({
                title: title,
                msg: msg,
                showType: 'show'
            });
        }
    },
    WindowOpen: function (windowId, options) {
        var defaults = {
            width: 500,                //宽度
            height: 400,            //高度
            iconCls: '',            //图标class
            collapsible: false,        //折叠
            minimizable: false,        //最小化
            maximizable: false,        //最大化
            resizable: false,        //改变窗口大小
            title: '窗口标题',        //窗口标题
            modal: true,            //模态    
            submit: function () {
                alert('写入执行的代码。');
            },
            html: '',
            onCloseEvent: function () { }
        }

        var options = $.extend(defaults, options);
        if (windowId == "") {
            var html = options.html;
            if (document.getElementById('windowContainer')) {
                $('<div id="windowContainer"></div>').appendTo('body');
            }
            $('#windowContainer').window({
                title: options.title, width: options.width, height: options.height, content: buildWindowContent(html, options.submit),
                collapsible: options.collapsible, minimizable: options.minimizable, maximizable: options.maximizable,
                modal: options.modal, iconCls: options.iconCls,
                onClose: options.onCloseEvent   // 窗口关闭事件
            }).window('open');

        } else {
            $('#' + windowId).window({
                title: options.title, width: options.width, height: options.height,
                collapsible: options.collapsible, minimizable: options.minimizable, maximizable: options.maximizable,
                modal: options.modal, iconCls: options.iconCls,
                onClose: options.onCloseEvent   // 窗口关闭事件
            }).window('open');
        }


        function buildWindowContent(contentHTML, fn) {
            var centerDIV = $('<div region="center" border="false" style="padding:5px;"></div>').html(contentHTML);

            $('<div class="easyui-layout" fit="true"></div>')
            .append(centerDIV)
            .append('<div region="south" border="false" style="padding-top:5px;height:40px; overflow:hidden; text-align:center;background:#fafafa;border-top:#eee 1px solid;">  <a iconCls="icon-ok">确定</a><a iconCls="icon-cancel">取消</a></div>')
            .appendTo($('#windowContainer').empty())
            .layout();

            $('.easyui-layout a[iconCls]').linkbutton();

            $('a[iconCls="icon-cancel"]').click(function () {
                $('#windowContainer').window('close');
            });

            $('a[iconCls="icon-ok"]').unbind('click').click(fn);
        }

    },
    WindowCloss: function (windowId) {
        if (windowId == "") {
            $('#windowContainer').window('close');
        } else {
            $('#' + windowId).window('close');
        }
    },
    ShowTransferWin: function (data) { // 弹出流转工单（客户、公共池）窗口，录音查询页面的评分窗口
        $('#win').show();
        this.WindowOpen('win', data);
        $('#formTransfer').find('#hidWorkOrderIds').val(data.workOrderIds);   // 工单查询页面：工单流转
        $('#formTransfer').find('#hidUserIds').val(data.userIds);   // 公共客户页面：分配客户
        $('#formTransfer').find('#showUserName').text(data.showTips);
        $('#hidCallId').val(data.callId);    // 录音查询页面：评分
        $('#formTransfer').find('#hidIsBatch').val(data.IsBatch);   // 工单查询页面：工单流转
        //console.log($('#formTransfer').find('#hidWorkOrderIds').val());
    },
    ValidateEmail: function (source) {        
        var emailreg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;        
        if (!emailreg.test(source)) {
            return false;
        } else {
            return true;
        }
    },
    ValidatePhone: function (source) {
        var pattern = /^1[34578]\d{9}$/;
        return pattern.test(source);
    },
    ValidateIdCard: function (source) {
        var d = 0;
        var l = source;
        var i = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙", 21: "辽宁", 22: "吉林", 23: "黑龙", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" };
        if (!/^\d{17}(\d|x)$/i.test(l)) {
            return false;
        }
        l = l.replace(/x$/i, "a");
        if (i[parseInt(l.substr(0, 2))] == null) {
            return false;
        }
        var j = l.substr(6, 4) + "-" + Number(l.substr(10, 2)) + "-" + Number(l.substr(12, 2));
        var m = new Date(j.replace(/-/g, "/"));
        if (j != (m.getFullYear() + "-" + (m.getMonth() + 1) + "-" + m.getDate())) {
            return false;
        }
        for (var k = 17; k >= 0; k--) {
            d += (Math.pow(2, k) % 11) * parseInt(l.charAt(17 - k), 11)
        }
        if (d % 11 != 1) {
            return false;
        }
        return true;
    },
    GetCurrencyEnum: function () {
        var currency = Array();
        currency[0] = "人民币,1";
        currency[1] = "美元,2";
        currency[2] = "英镑,6";
        currency[3] = "欧元,3";
        currency[4] = "纽币,18";
        currency[5] = "澳币,7";
        currency[6] = "韩元,16";
        currency[7] = "日元,5";
        currency[8] = "加元,8";
        currency[9] = "港币,4";
        return currency;
    },
    BuilderCurrencyData: function (currencyId, seleId) {

        var currency = utils.GetCurrencyEnum();
        for (var i = 0; i < currency.length; i++) {
            if (currency[i] != null) {
                var option = new Option(currency[i].split(",")[0], currency[i].split(",")[1]);

                document.getElementById(currencyId).options[document.getElementById(currencyId).options.length] = option;
            }
        }

        $("#" + currencyId).val(1);
    },
    //复制到剪切板,只支持IE
    copyToClipboard: function (maintext) {
        var msg = "以下内容已经复制到剪贴板\n" + maintext;
        if (window.clipboardData) {
            window.clipboardData.setData("Text", maintext);
            //$.messager.alert("复制成功", );
            $.messager.show({
                title: "复制成功",
                msg: msg,
                showType: 'show'
            });
        } else if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch (e) {
                //alert("该浏览器不支持一键复制！n请手工复制文本框链接地址～");
                //$.messager.alert("复制失败", "该浏览器不支持一键复制！n请手工复制文本框链接地址～");
                //$.messager.alert("复制失败", "浏览器不支持,请手工复制:\n\n" + maintext);
                utils.copyFailWindow(maintext);
            }

            var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;
            var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;
            trans.addDataFlavor('text/unicode');
            var str = new Object();
            var len = new Object();
            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            var copytext = maintext;
            str.data = copytext;
            trans.setTransferData("text/unicode", str, copytext.length * 2);
            var clipid = Components.interfaces.nsIClipboard;
            if (!clip) return false;
            clip.setData(trans, null, clipid.kGlobalClipboard);
            $.messager.show({
                title: "复制成功",
                msg: msg,
                showType: 'show'
            });
        }
        else {
            //$.messager.alert("复制失败", "浏览器不支持,请手工复制:\n\n" + maintext);
            utils.copyFailWindow(maintext);
        }
        //alert("以下内容已经复制到剪贴板nn" + maintext);

    },
    copyFailWindow: function (maintext) {
        var mask = document.createElement("div");//js新建元素
        mask.setAttribute("id", "copyFailDiv");//给元素加id
        document.body.appendChild(mask);//把元素放进body标签里面
        if ($("#copyFailText").length == 0) {
            var input = document.createElement("input");
            input.setAttribute("id", "copyFailText");
            $("#copyFailDiv").append(input);
        }
        $('#copyFailText').textbox({ multiline: true, width: 280, height: 190 });
        $('#copyFailText').textbox("setValue", maintext);
        //$('#copyFailText').textbox("focus");
        //utils.WindowOpen('copyFailDiv', { title: '复制失败', height: 450, width: 450, closed: true })
        $('#copyFailDiv').dialog({
            title: '复制失败,请手工复制!',
            width: 300,
            height: 200,
            closed: false,
            cache: false,
            resizable: true,
            shadow: true
        });
    },//时间戳转换成年月日时间--庞军伟 2016-12-15
    jsonTimeStamp: function (milliseconds) {
        //alert(milliseconds);
        milliseconds = milliseconds.replace(/[^0-9]/g, '');
        if (milliseconds != "" && milliseconds != null
                && milliseconds != "null") {
            var datetime = new Date();
            datetime.setTime(milliseconds);
            var year = datetime.getFullYear();
            var month = datetime.getMonth() + 1 < 10 ? "0"
                    + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
            var date = datetime.getDate() < 10 ? "0" + datetime.getDate()
                    : datetime.getDate();
            var hour = datetime.getHours() < 10 ? "0" + datetime.getHours()
                    : datetime.getHours();
            var minute = datetime.getMinutes() < 10 ? "0"
                    + datetime.getMinutes() : datetime.getMinutes();
            var second = datetime.getSeconds() < 10 ? "0"
                    + datetime.getSeconds() : datetime.getSeconds();
            return year + "-" + month + "-" + date + " " + hour + ":" + minute
                    + ":" + second;
        } else {
            return "";
        }
    },//转换成日期，不返回时间
    jsonTime: function (milliseconds) {
        //alert(milliseconds);
        milliseconds = milliseconds.replace(/[^0-9]/g, '');
        if (milliseconds != "" && milliseconds != null
                && milliseconds != "null") {
            var datetime = new Date();
            datetime.setTime(milliseconds);
            var year = datetime.getFullYear();
            var month = datetime.getMonth() + 1 < 10 ? "0"
                    + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
            var date = datetime.getDate() < 10 ? "0" + datetime.getDate()
                    : datetime.getDate(); 
            return year + "-" + month + "-" + date;
        } else {
            return "";
        }
    }
};